package com.haiheng.module_main.mode

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.constant.AppConstant
import com.haiheng.common.constant.RourePage
import com.haiheng.library.log.LogUtils
import com.haiheng.library_base.http.Domain
import com.haiheng.library_base.http.HttpRequest
import com.haiheng.library_base.http.HttpResponse
import com.haiheng.library_base.http.api
import com.haiheng.library_base.http.postJson
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.db.BookInfoBean
import com.haiheng.library_base.db.BookInfoSub
import com.haiheng.library_base.db.BookRetirementData
import com.haiheng.library_base.db.BookWithdrawalRecordTable
import com.haiheng.library_base.db.KVDatabase
import com.haiheng.module_main.bean.req.Asset
import com.haiheng.module_main.bean.req.AssetOffInfo
import com.haiheng.module_main.bean.req.BookAssetOffLocationReq
import com.haiheng.module_main.bean.req.BookRetirementPageRes
import com.haiheng.module_main.bean.req.PageQueryReq
import com.haiheng.module_main.bean.req.SourceInfo
import com.haiheng.module_main.bean.req.Wherejson
import kotlinx.coroutines.launch

/**
 *
 * @Des:剔旧
 * @Author: hwz
 * @Date:2023/6/26 0026
 * @Version: 1.0
 */
class BookRetirementViewModel(private val bookInfoViewModel: BookInfoViewModel) : BaseViewModel() {
    var _bookRetirementData = MutableLiveData<List<BookRetirementData>>(emptyList())

    fun searchBookRetirementByOfflineMode() {
        api {
            var bookRetirementData = KVDatabase.getDb().getBookRetirementDao().queryAll()
            _bookRetirementData.postValue(bookRetirementData)
        }
    }

    /**
     * 剔旧 列表查询
     *
     */
    fun searchBookRetirement(){
        if (AppConstant.isOpenOfflineMode()){
            searchBookRetirementByOfflineMode()
        }else{
            queryBookRetirementByNet()
        }
    }

    /**
     * 在线查询剔旧列表并同步到本地
     *
     */
    fun queryBookRetirementByNet() {
        api {
            var pageQueryReq = PageQueryReq()
            pageQueryReq.page = 1
            pageQueryReq.length = 100000
            var wherejson = arrayListOf<Wherejson>()
            var orgCodejson = Wherejson()
            orgCodejson.conditionalType = 0 //0精确查询，1，模糊查询
            orgCodejson.fieldName = "OrgCode"
            orgCodejson.fieldValue = AppConstant.getLibraryCode()
            wherejson.add(orgCodejson)
            var taskTypejson = Wherejson()
            taskTypejson.conditionalType = 0
            taskTypejson.fieldValue = "剔旧"
            taskTypejson.fieldName = "taskType"
            wherejson.add(taskTypejson)
            var statejson = Wherejson()
            statejson.conditionalType = 0
            statejson.fieldValue = "0"
            statejson.fieldName = "state"
            wherejson.add(statejson)
            pageQueryReq.wherejson = wherejson
            val request = HttpRequest(API.PATH.SEARCH_BOOK_RETIREMENT)
                .putHeader(Domain.KEY_NAME, Domain.VALUE_DEFUlT)
                .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                .setJsonObjec(pageQueryReq)
            var response = postJson<BookRetirementPageRes>(request)
            if (response.isSuccess == true && response.data != null && response.data.size > 0) {
                LogUtils.e("查询剔旧成功：${response.data.size}")
                _bookRetirementData.postValue(response.data)
                synLocationRetirementData(response.data)
            } else {
                _bookRetirementData.postValue(listOf())
                synLocationRetirementData(listOf())
                LogUtils.w("获取剔旧信息失败:${response.toJson()}")
            }
        }
    }

    /**
     * 同步更新本地剔旧数据
     * 1.同步之前先将之前剔旧数据置空
     * 2.更新最新剔旧数据
     *
     */
    fun synLocationRetirementData(data: List<BookRetirementData>) {
        api {
            var db = KVDatabase.getDb()
            var bookInfoDao = db.bookInfoDao()
            var oldRetirementList =
                bookInfoDao.getBookInfoListByCondition("isAlarmed", true.toString())
            oldRetirementList.forEach {
                it.isRetirment = false
            }
            bookInfoDao.updateBookInfo(*oldRetirementList.toTypedArray())
            data.forEach {
                var b = bookInfoDao.getBookInfoByBarCode(it.objInfo)
                if (b != null){
                    b.isRetirment = true
                    bookInfoDao.updateBookInfo(b)
                }
            }
            db.getBookRetirementDao().deleteAll()
            db.getBookRetirementDao().insertAll(data)
        }
    }

    /**
     * 更新剔旧列表数据 构建统一书籍列表数据模型
     *
     */
    fun uopdataRetirementList() {
        api {
            var list = mutableListOf<BookInfoBean>()
            _bookRetirementData.value?.forEach {
                var b = BookInfoBean()
                b.barCode = it.objInfo
                b.bookTitle = it.objName
                b.isRetirment = true
                var bookInfoSub = BookInfoSub()
                bookInfoSub.name = it.objWhereName
                b.fixedContainerSub = bookInfoSub
                list.add(b)
            }
            bookInfoViewModel._bookListData.postValue(list)
        }
    }

    /**
     * 离线模式剔旧
     *
     */
    fun bookRetirementByOffLine(){
        api {
            bookInfoViewModel.bookListData.value?.forEach {
                if (it.isSelect){
                    var b = BookWithdrawalRecordTable()
                    b.barCode = it.barCode
                    b.recordType = RourePage.BOOK_RETIREMENT.name
                    b.dataSourceType = "6"
                    b.orgCode = AppConstant.getLibraryCode()
                    b.assetOffType = 2 // 0下架（书列表）  1下架（按层）   2剔旧（书列表）
                    var db = KVDatabase.getDb()
                    //删除剔旧数据
                    db.getBookRetirementDao().deleteBookRetirementByBarCode(it.barCode.toString())
                    //添加剔旧记录
                    var result = db.getBookWithdrawalRecordDao().insert(b)
                    if (result < 1){
                        bookInfoViewModel.showMsg.postValue("本地剔旧失败:${result}")
                    }
                }
            }
            bookInfoViewModel.showMsg.postValue("剔旧:本地剔旧完成")
        }
    }


    /**
     * 进行剔旧操作
     *
     */
    fun bookRetirement() {
        if (AppConstant.isOpenOfflineMode()){
            bookRetirementByOffLine()
            return
        }
        var req = BookAssetOffLocationReq()
        var sourceInfo = SourceInfo()
        sourceInfo.dataSourceType = "6"
        sourceInfo.orgCode = AppConstant.getLibraryCode()
        var assetOffInfos = arrayListOf<AssetOffInfo>()
        var assetOffInfo = AssetOffInfo()
        var assets = arrayListOf<Asset>()
        bookInfoViewModel.bookListData.value?.forEachIndexed { index, value ->
            LogUtils.e("索引 ${index} 的值为 ${value}")
            if (value.isSelect) {
                var asset = Asset()
                asset.barCode = value.barCode.toString()
                assets.add(asset)
            }
        }
        assetOffInfo.assets = assets
        assetOffInfos.add(assetOffInfo)
        req.sourceInfo = sourceInfo
        req.assetOffType = 2 // 0下架（书列表）  1下架（按层）   2剔旧（书列表）
        req.assetOffInfos = assetOffInfos
        api {
            viewModelScope.launch {
                val request = HttpRequest(API.PATH.BOOK_ASSET_OFF_LOCATION)
                    .putHeader(Domain.KEY_NAME, Domain.VALUE_DEFUlT)
                    .putHeader(API.PARAM.PARAM_HEADER_TOKEN, AppConstant.getToken())
                    .setJsonObjec(req)
                var response = postJson<HttpResponse>(request)
                if (response.isSuccess == true) {
                    LogUtils.e("书籍剔旧成功")
                    bookInfoViewModel.showMsg.postValue("剔旧:${response.message}")
                } else {
                    if (response.message.isNotBlank()) {
                        bookInfoViewModel.showMsg.postValue(response.message)
                    } else {
                        bookInfoViewModel.showMsg.postValue(response.errorMsg)
                    }
                    LogUtils.w("书籍剔旧失败:${response.toJson()}")
                }
            }
        }
    }
}